package com.ymttest.utils.compare;

import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.ymttest.utils.YMTDateUtil;

public class CompareThreadPool {
	private ThreadPoolExecutor threadPoolExecutor;
	
	public CompareThreadPool(int corePoolSize){
		threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, corePoolSize*2, Long.MAX_VALUE,
				TimeUnit.SECONDS, new LinkedBlockingQueue<>());
		
	}
	
	public long runTask(List<Runnable> runList) {
		Date startDate = YMTDateUtil.getDate();
		runList.forEach(ele -> {threadPoolExecutor.execute(ele);});

		threadPoolExecutor.shutdown();// 只是不能再提交新任务，等待执行的任务不受影响

		try {
			boolean loop = true;
			do { // 等待所有任务完成
				loop = !threadPoolExecutor.awaitTermination(1, TimeUnit.SECONDS); // 阻塞，直到线程池里所有任务结束
			} while (loop);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Date endDate = YMTDateUtil.getDate();
		
		return (endDate.getTime() - startDate.getTime()) / 1000;
	}
	
}
